﻿
// 日期格式化
Date.prototype.format = function (format) {
    /* 
    * eg:format="yyyy-MM-dd hh:mm:ss"; 
    */
    var o = {
        "M+": this.getMonth() + 1, // month  
        "d+": this.getDate(), // day  
        "h+": this.getHours(), // hour  
        "m+": this.getMinutes(), // minute  
        "s+": this.getSeconds(), // second  
        "q+": Math.floor((this.getMonth() + 3) / 3), // quarter  
        "S": this.getMilliseconds()
        // millisecond  
    }

    if (/(y+)/.test(format)) {
        format = format.replace(RegExp.$1, (this.getFullYear() + "").substr(4 - RegExp.$1.length));
    }

    for (var k in o) {
        if (new RegExp("(" + k + ")").test(format)) {
            format = format.replace(RegExp.$1, RegExp.$1.length == 1 ? o[k] : ("00" + o[k]).substr(("" + o[k]).length));
        }
    }
    return format;
};

Date.prototype.compare = function (dateString1, dateString2) {
    var result = 0;
    var regEx = new RegExp("\\-", "gi");
    var date1 = new Date(dateString1.replace(regEx, "/"));
    var date2 = new Date(dateString2.replace(regEx, "/"));

    var diff = Date.parse(date1) - Date.parse(date2);
    if (diff < 0) {
        result = -1;
    }
    else if (diff > 0) {
        result = 1;
    }

    return result;
}

Date.prototype.addDays = function (thisValue, value) {
    var regEx = new RegExp("\\-", "gi");
    var dateThis = new Date(thisValue.replace(regEx, "/"));
    dateThis.setDate(dateThis.getDate() + Number(value));
    return dateThis.format('yyyy-MM-dd');
}

// 数字缺位补零
Number.prototype.zeroize = function (numberLength) {
    var result = this.toString();
    var length = Number(numberLength);
    if (length > 0) {

        if (result.length < length) {
            var missLength = length - result.length;
            for (var j = 0; j < missLength; j++) {
                result = '0' + result;
            }
        }
    }
    return result;
};

// 字符串处理
String.prototype.trimStart = function (trimStr) {
    if (!trimStr) { return this; }
    var temp = this;
    while (true) {
        if (temp.substr(0, trimStr.length) != trimStr) {
            break;
        }
        temp = temp.substr(trimStr.length);
    }
    return temp;
};

String.prototype.trimEnd = function (trimStr) {
    if (!trimStr) { return this; }
    var temp = this;
    while (true) {
        if (temp.substr(temp.length - trimStr.length, trimStr.length) != trimStr) {
            break;
        }
        temp = temp.substr(0, temp.length - trimStr.length);
    }
    return temp;
};

String.prototype.trim = function (trimStr) {
    var temp = trimStr;
    if (!trimStr) { temp = " "; }
    return this.trimStart(temp).trimEnd(temp);
};

String.prototype.resolveClientUrl = function (url) {
    var result = url;
    if (url && url.trimStart) {
        result = url.trimStart('~');
    }
    return result;
};

var amCommon = {

    // 判断是否对象
    isObject: function (obj) {
        return Object.prototype.toString.call(obj) === '[object Object]';
    },

    // 判断是否数组
    isArray: function (obj) {
        return Object.prototype.toString.call(obj) === '[object Array]';
    },

    // 判空
    notEmpty: function (obj) {
        return (obj != null && obj != undefined && obj.toString().length > 0);
    },

    // 小数判断相等
    floatEqual: function (source, target) {
        var diff = Number(source) - Number(target);
        return (diff <= 0.000001 && diff >= -0.000001);
    },

    htmlEncode: function (str) {
        if (str == null || str == undefined || str.toString().length <= 0) return "";
        var s = str.replace(/&/g, "&amp;");
        s = s.replace(/</g, "&lt;");
        s = s.replace(/>/g, "&gt;");
        s = s.replace(/ /g, "&nbsp;");
        s = s.replace(/\'/g, "&#39;");
        s = s.replace(/\"/g, "&quot;");
        s = s.replace(/\\/g, "&#92;");
        return s;
    },

    htmlDecode: function (str) {
        if (str == null || str == undefined || str.toString().length <= 0) return "";
        var s = str.replace(/&amp;/g, "&");
        s = s.replace(/&lt;/g, "<");
        s = s.replace(/&gt;/g, ">");
        s = s.replace(/&nbsp;/g, " ");
        s = s.replace(/&#39;/g, "\'");
        s = s.replace(/&quot;/g, "\"");
        s = s.replace(/&#92;/g, "\\");
        return s;
    },

    business: {
        // 业务数据筛选条件
        selectionFilter: function () {
            // 选择业务数据时只查询指定状态(511待受理,910已过帐,911已发布)的数据 // mark 不能硬编码
            return '';
            //return '{"field":"SystemFormStatus","op":"fieldinarray","value":"511,910,911"},';
        },

        ajaxError: function (result) {
            var message = '很抱歉，操作出现异常！请联系管理员。';
            if (result) {
                if (result.responseJSON && result.responseJSON.ExceptionMessage) {
                    message = result.responseJSON.ExceptionMessage;
                }
                else if (result.responseText) {
                    message = result.responseText;
                }
            }

            $.messager.alert('错误', message, 'error');
        }
    }

};

// 返回数组最后一个元素
Array.prototype.getLast = function () {
    var result;
    if (this.length > 0) {
        result = this[this.length - 1];
    }
    return result;
};

// 判断数组中是否包含指定元素
Array.prototype.contains = function (element) {
    if (this.length > 0) {
        for (var i = 0; i < this.length; i++) {
            if (this[i] == element) {
                return true;
            }
        }
    }
    return false;
};

// 从选项数组获取指定父值的选项列表
Array.prototype.getSelectionsByParent = function (value) {
    var result = new Array();
    if (this.length > 0 && value > 0) {
        for (var i = 0; i < this.length; i++) {
            if (this[i] != null
                && this[i] != undefined
                && this[i].parent == value) {
                result.push(this[i]);
            }
        }
    }
    return result;
};

// 从选项数组获取指定值的选项
Array.prototype.getSelectionByValue = function (value) {
    if (this.length > 0 && value > 0) {
        for (var i = 0; i < this.length; i++) {
            if (this[i] != null
                && this[i] != undefined
                && this[i].value == value) {
                return this[i];
            }
        }
    }
    return null;
};

// 从选项数组获取指定文本的选项
Array.prototype.getSelectionByText = function (text) {
    if (this.length > 0 && amCommon.notEmpty(text)) {
        for (var i = 0; i < this.length; i++) {
            if (this[i] != null
                && this[i] != undefined
                && this[i].text == text) {
                return this[i];
            }
        }
    }
    return null;
};

// 判断选项数组中是否包含指定值
Array.prototype.containsSelectionValue = function (value) {
    if (this.length > 0) {
        for (var i = 0; i < this.length; i++) {
            if (this[i] != null
                && this[i] != undefined
                && (value == undefined
                    || this[i].value == value)) {
                return true;
            }
        }
    }
    return false;
};

// 判断选项数组中是否包含指定元素
Array.prototype.containsSelection = function (element) {
    if (element) {
        return this.containsSelectionValue(element.value);
    }
    return false;
};

// 合并两个数组，排除重复
Array.prototype.merge = function (arr, removeZeroLength) {
    var result = this;

    if (arr && arr.length > 0) {
        for (var i = 0; i < arr.length; i++) {
            if (arr[i] != null
                && arr[i] != undefined
                && (!removeZeroLength || arr[i].toString().length > 0)
                && !result.contains(arr[i])) {
                result.push(arr[i]);
            }
        }
    }

    return result;
};

// 合并两个选项数组，排除重复
Array.prototype.mergeSelections = function (arr, removeZeroLength) {
    var result = this;

    if (arr && arr.length > 0) {
        for (var i = 0; i < arr.length; i++) {
            if (arr[i] != null
                && arr[i] != undefined
                && (!removeZeroLength || arr[i].toString().length > 0)
                && !result.containsSelection(arr[i])) {
                result.push(arr[i]);
            }
        }
    }

    return result;
};

// 移除数组中的空值，包括null、undefined、空字符串
Array.prototype.removeEmpty = function () {
    var result = new Array();

    for (var i = 0; i < this.length; i++) {
        if (amCommon.notEmpty(this[i])) {
            result.push(this[i]);
        }
    }

    return result;
};

// 初始化键盘输入常量
Window.prototype.typeKeys = {
    'enter': 13,
    'tab': 9,
    'comma': 188,
    'backspace': 8,
    'leftarrow': 37,
    'uparrow': 38,
    'rightarrow': 39,
    'downarrow': 40
};

// 停止事件冒泡
Window.prototype.exStopBubble = function (e) {
    if (e && e.stopPropagation) {
        //W3C取消冒泡事件
        e.stopPropagation();
    } else if (window.event) {
          window.event.cancelBubble = true;
        }

    //if (window.event) {
    //    window.event.cancelBubble = true;
    //}else if (event.stopPropagation) {
    //    // this code is for Mozilla and Opera 
    //    event.stopPropagation();
    //}
};

// 键盘输入是否为操作类输入，比如上下左右箭头、回车等
Window.prototype.typeKeyIsAction = function (keyCode) {
    if (keyCode == window.typeKeys.downarrow
        || keyCode == window.typeKeys.uparrow
        || keyCode == window.typeKeys.leftarrow
        || keyCode == window.typeKeys.rightarrow
        || keyCode == window.typeKeys.enter
        || keyCode == window.typeKeys.tab
        || keyCode == window.typeKeys.comma) {
        return true;
    }
    return false;
};

Window.prototype.createArray = function () {
    return new Array();
}

// 获取最近一层弹出框信息
Window.prototype.getLastLayer = function () {
    var lastLayer;
    var dialogArray = top.document.exPopupDialogs;
    if (amCommon.isArray(dialogArray)) {
        lastLayer = dialogArray.getLast();
    }
    return lastLayer;
}

// 显示对话框
Window.prototype.showDialog = function (title, src, width, height, resizable, minimizable, maximizable) {
    var dialogContainer = top.$('<div style="width:' + width + 'px; height:' + height + 'px"></div>').appendTo(top.document.body);

    var dialogArray = top.document.exPopupDialogs;
    if (!amCommon.isArray(dialogArray)) {
        // 不直接使用new Array()，避免“不能执行已释放Script的代码”问题
        top.document.exPopupDialogs = top.createArray();
        dialogArray = top.document.exPopupDialogs;
    }

    var newLayer = new Object();
    newLayer.windowPopup = dialogContainer;
    newLayer.windowParent = window;
    newLayer.windowLayers = dialogArray.length + 1;
    dialogArray.push(newLayer);

    dialogContainer.window({
        closed: true,
        modal: true,
        resizable: (resizable ? resizable : false),
        minimizable: (minimizable ? minimizable : false),
        maximizable: (maximizable ? maximizable : false),
        title: title,
        content: '<iframe width="100%" height="99.4%" src="' + src + '" frameBorder="0"></iframe>',
        //tools: [{
        //    iconCls: 'icon-reload',
        //    handler: function () {
        //        var lastLayer = top.getLastLayer();
        //        if (lastLayer && lastLayer.windowPopup) {
        //            lastLayer.windowPopup.window('refresh');
        //        }
        //    }
        //}],
        onClose: function () {
            // 在窗口关闭时移除层信息
            var lastLayer;
            var dialogArray = top.document.exPopupDialogs;
            if (amCommon.isArray(dialogArray)) {
                lastLayer = dialogArray.pop();
                if (lastLayer && lastLayer.windowPopup) {
                    var frame = $('iframe', lastLayer.windowPopup);
                    if (frame.length > 0) {
                        frame[0].contentWindow.document.write('');
                        frame[0].contentWindow.close();
                        frame.remove();

                        if ($.browser && $.browser.msie && CollectGarbage) {
                            CollectGarbage();
                        }
                    }
                    lastLayer.windowPopup.remove();
                    lastLayer.windowPopup = undefined;
                }
            }
        }
    });
    dialogContainer.window('open');
    return newLayer;
};

// 关闭对话框
Window.prototype.closeDialog = function () {
    var lastLayer = top.getLastLayer();
    if (lastLayer && lastLayer.windowPopup) {
        lastLayer.windowPopup.window('close');
    }
    return lastLayer;
};

// 关闭并刷新父窗口
Window.prototype.closeRefreshDialog = function (returnValue) {

    var lastLayer = top.closeDialog();
    if(lastLayer!=undefined){
    if (lastLayer.windowParent) {

        // 若父窗口是DataGrid，则刷新Grid；否则刷新父页面
        var parentCallbackString = lastLayer.windowParent.dialogCallbackString;
        var parentGridHandler = lastLayer.windowParent.gridListHandler;
        if (parentGridHandler
            && parentGridHandler.refreshGrid) {
            // 刷新Grid
            parentGridHandler.refreshGrid();

            // 若父页面有回调函数，则执行回调
            if (parentCallbackString) {
                eval('lastLayer.windowParent.' + parentCallbackString + '(' + returnValue + ')');
            }
        }
        else {

            // 若父页面有回调函数，则执行回调
            var parentFrame = lastLayer.windowParent.frameElement;
            if (parentCallbackString) {
                function parentCallbackBind() {
                    eval('this.contentWindow.' + parentCallbackString + '(' + returnValue + ')');
                    $(parentFrame).unbind('load', parentCallbackBind);
                    parentFrame = undefined;
                }

                $(parentFrame).bind('load', parentCallbackBind);
            }

            // 刷新页面
            lastLayer.windowParent.location.reload();
        }

        lastLayer.windowParent.dialogCallbackString = undefined;
        lastLayer.windowParent = undefined;
    }
    } else {
        alert("修改成功");
    }
    return lastLayer;
};

// 显示用户选择对话框
Window.prototype.showUserDialog = function (userIDs, isSingleSelect, roleList) {
    if (isSingleSelect == true) {
        var usageType = "SingleSelection";
    }

    var url = '/Authority/UserSelector/UserSelector?usageType=' + usageType + '&UserList=' + userIDs;
    if (roleList) {
        url += '&RoleList=' + roleList;
    }

    // 此处不能使用top.showDialog，不然无法准确记录windowParent
    return window.showDialog('选择用户（点击部门或输入查询条件进行查询）', url, 950, 550);
};

// 显示业务数据列表对话框
Window.prototype.showBusinessList = function (formID, title, selectedValues, filterItemID, filterItemValue, usageType, extraFilter) {
   
    if (!amCommon.notEmpty(title)) {
        title = '查看记录';
    }

    if (!amCommon.notEmpty(usageType)) {
        usageType = 'SingleSelection';
    }

    var url = formID;
    var paraChar = '?';
    if (!isNaN(formID)) {
        paraChar = '&';
       
        url = '/Business/ListData/ListPage?FormID=' + formID;
    }
    else if(url.indexOf('?')>=0)
    {
        paraChar = '&';
    }

    if (amCommon.notEmpty(usageType)) {
        url += paraChar + 'UsageType=' + usageType;
    }

    if (amCommon.notEmpty(selectedValues)) {
        url += '&SelectIDs=' + selectedValues;
    }

    if (filterItemID > 0 && amCommon.notEmpty(filterItemValue)) {
        url += '&FilterItemID=' + filterItemID + '&FilterItemValue=' + filterItemValue
    }

    if (amCommon.notEmpty(extraFilter)) {
        url += '&ExtraFilter=' + extraFilter;
    }
    return window.showDialog(title, url, 950, 550);
};

// 显示业务数据选择对话框
Window.prototype.showBusinessDialog = function (formID, formName, selectedValues, filterItemID, filterItemValue, usageType, extraFilter) {
    var title = '选择记录(双击行即可选中)';
    if (amCommon.notEmpty(formName)) {
        title = '选择' + formName + '(双击行即可选中)';
    }

    return window.showBusinessList(formID, title, selectedValues, filterItemID, filterItemValue, usageType, extraFilter);
};

// 显示报表数据选择对话框
Window.prototype.showSummaryDialog = function (formID, formName, selectedValues, filterItemID, filterItemValue, usageType, extraFilter) {
    var title = '选择记录(双击行即可选中)';
    if (amCommon.notEmpty(formName)) {
        title = '选择' + formName + '(双击行即可选中)';
    }

    if (!amCommon.notEmpty(usageType)) {
        usageType = 'MultiSelection';
    }

    var url = '/Business/SummaryData/SummaryPage?FormID=' + formID;

    if (amCommon.notEmpty(usageType)) {
        url += '&UsageType=' + usageType;
    }

    if (amCommon.notEmpty(selectedValues)) {
        url += '&SelectIDs=' + selectedValues;
    }

    if (filterItemID > 0 && amCommon.notEmpty(filterItemValue)) {
        url += '&FilterItemID=' + filterItemID + '&FilterItemValue=' + filterItemValue
    }

    if (amCommon.notEmpty(extraFilter)) {
        url += '&ExtraFilter=' + extraFilter;
    }

    return window.showDialog(title, url, 950, 550);
};

// 显示新建、编辑、查看业务数据对话框
Window.prototype.showBusinessForm = function (title, url,width,height) {
    if (!amCommon.notEmpty(title)) {
        title = '查看记录';
    }
    if(!width){
        width=950
    }
    if(!height){
        height=610
    }

    return window.showDialog(title, url, width, height);
};


(function () {
    if (!($.fn.combotree) || !($.fn.combotree.defaults)) {
        return;
    }

    // 设置Combotree查询功能
    $.extend($.fn.combotree.defaults.keyHandler, {
        query: function (q) {
            var t = $(this).combotree('tree');
            t.tree('expandAll');
            var nodes = t.tree('getChildren');
            for (var i = 0; i < nodes.length; i++) {
                var node = nodes[i];
                if (node.text.indexOf(q) >= 0) {
                    $(node.target).show();
                } else {
                    $(node.target).hide();
                }

                // 用户输入的字符刚刚匹配某项则自动选中
                if (node.text == q) {
                    t.tree('select', node.target);
                    $(this).combotree('setValue', node.id);
                }
            }

            var opts = $(this).combotree('options');
            if (!opts.hasSetEvents) {
                opts.hasSetEvents = true;
                var onShowPanel = opts.onShowPanel;
                opts.onShowPanel = function () {
                    var nodes = t.tree('getChildren');
                    for (var i = 0; i < nodes.length; i++) {
                        $(nodes[i].target).show();
                    }
                    onShowPanel.call(this);
                }
                $(this).combo('options').onShowPanel = opts.onShowPanel;
            }
        }
    });

    //扩展datagrid，在editors中使用combogrid
    $.extend($.fn.datagrid.defaults.editors, {
        combogrid: {
            init: function (container, options) {
                var input = $('<input type="text" class="datagrid-editable-input">').appendTo(container);
                input.combogrid(options);
                return input;
            },
            destroy: function (target) {
                $(target).combogrid('destroy');
            },
            getValue: function (target) {
                // 支持多选
                if ($(target).combogrid('options').multiple == true) {
                    var values = $(target).combogrid('getValues');

                    if (!values || values.length <= 0) {
                        values = new Array;
                    }
                    else if (values.length == 1) {
                        // 避免误把多个序列号保存为一个字符串的情况
                        values = values[0].toString().split(',');
                    }

                    // 移除空值
                    if (values.removeEmpty) {
                        values = values.removeEmpty();
                    }
                    return values;
                }
                else {
                    return $(target).combogrid('getValue');
                }
            },
            getValues: function (target) {
                // 移除空值
                var values = $(target).combogrid('getValues');
                if (values && values.removeEmpty) {
                    values = values.removeEmpty();
                }
                return values;
            },
            setValue: function (target, value) {
                $(target).combogrid('setValue', value);
            },
            setValues: function (target, value) {
                $(target).combogrid('setValues', value);
            },
            resize: function (target, width) {
                $(target).combogrid('resize', width);
            }
        }
    });

    $.extend($.fn.combobox.methods, {
        // 扩展实现combobox实现清空并禁用、启用，若有第一个参数就不清空原值
        exDisable: function (jq, param) {
            return jq.each(function () {
                var control = $(this);
                if (this.exComboClear) {
                    this.exComboClear.showClearButton(null);
                }
                if (!param || param.length <= 0) {
                    control.combobox('setValue', '');
                }
                control.combo('options').exUseOriginDisable = true;
                control.combobox("disableValidation");
                control.combobox('validate');
                control.combobox('disable');
            });
        },
        exEnable: function (jq, param) {
            return jq.each(function () {
                var control = $(this);
                control.combobox('enable');
                control.combobox("enableValidation");
                control.combobox('validate');
            });
        },

        // 参数:值、显示名称
        exSetValue: function(jq, value, text) {
            return jq.each(function () {
                if (value == null || text == null) {
                    return;
                }

                var control = $(this);
                var options = control.combobox("options");
                if (!options.data || !options.data.mergeSelections) {
                    options.data = new Array();
                }
                options.data = options.data.mergeSelections([{ value: value, text: text }]);
                control.combobox("loadData", options.data);

                control.combobox('setValue', value);
            });
        }
    });

    $.extend($.fn.datebox.methods, {
        // 扩展实现datebox实现清空并禁用、启用，若有第一个参数就不清空原值
        exDisable: function (jq, param) {
            return jq.each(function () {
                var control = $(this);
                if (this.exComboClear) {
                    this.exComboClear.showClearButton(null);
                }
                if (!param || param.length <= 0) {
                    control.datebox('setValue', '');
                }
                control.combo('options').exUseOriginDisable = true;
                control.datebox("disableValidation");
                control.datebox('validate');
                control.datebox('disable');
            });
        },
        exEnable: function (jq, param) {
            return jq.each(function () {
                var control = $(this);
                control.datebox('enable');
                control.datebox("enableValidation");
                control.datebox('validate');
            });
        }
    });

    $.extend($.fn.validatebox.methods, {
        // 扩展实现datebox实现清空并禁用、启用，若有第一个参数就不清空原值
        exDisable: function (jq, param) {
            return jq.each(function () {
                var control = $(this);
                if (!param || param.length <= 0) {
                    control.val('');
                }
                control.validatebox("disableValidation");
                control.validatebox('validate');
                control.attr('disabled', 'disabled');
            });
        },
        exEnable: function (jq, param) {
            return jq.each(function () {
                var control = $(this);
                control.removeAttr('disabled');
                control.validatebox("enableValidation");
                control.validatebox('validate');
            });
        }
    });
})(jQuery);

// 对Combo控件增加创建型序列号功能
var comboSerialNumberFunction = {
    initControl: function (element, itemName, disable) {

        if (!element
            || element.exHasSerialNumberFunc) {
            return;
        }

        element.exHasSerialNumberFunc = true;
        var comboGrid = $(element).combogrid('grid');
        var comboPanel = $(element).combo('panel');

        if (disable != true) {
            var btnMultiGenerate = comboPanel.find('#_ExChildGridToolbar_Multi_' + itemName);
            btnMultiGenerate.click(function () {
                comboSerialNumberFunction.endEdit(comboGrid, true);

                var newLayer = window.showDialog('设置序列号生成规则', '/Business/SystemView/SerialNumberCreation', 650, 350);
                newLayer.updateSerialNumberValue = function (serialNumbers) {
                    if (serialNumbers && serialNumbers.length > 0) {

                        // 加入到已有序列号中，并且去除重复
                        var existsRows = comboGrid.datagrid('getRows');
                        var existsNumber = existsRows.length;
                        for (var i = 0; i < serialNumbers.length; i++) {
                            if (serialNumbers[i] == null || serialNumbers[i] == undefined) {
                                continue;
                            }
                            var currentSerial = serialNumbers[i].toString();

                            var isExists = false;
                            for (var j = 0; j < existsNumber; j++) {
                                var existsSerial = existsRows[j];
                                if (existsSerial != null
                                    && existsSerial != undefined
                                    && existsSerial.text == currentSerial) {
                                    isExists = true;
                                    break;
                                }
                            }

                            if (!isExists) {
                                existsRows.push({ text: currentSerial });
                            }
                        }

                        if (existsRows.length > 0) {
                            comboGrid.datagrid('loadData', existsRows);
                        }
                    }

                    top.closeDialog();
                };
            });

            var btnAdd = comboPanel.find('#_ExChildGridToolbar_Add_' + itemName);
            btnAdd.click(function () {
                if (comboSerialNumberFunction.endEdit(comboGrid)) {
                    comboGrid.datagrid('appendRow', { text: '' });
                    var editIndex = comboGrid.datagrid('getRows').length - 1;
                    comboGrid.datagrid('selectRow', editIndex).datagrid('beginEdit', editIndex);
                    comboGrid[0].exEditingRowIndex = editIndex;
                }
            });

            var btnClearAll = comboPanel.find('#_ExChildGridToolbar_Clear_' + itemName);
            btnClearAll.click(function () {
                comboSerialNumberFunction.endEdit(comboGrid, true);
                var rowNumber = comboGrid.datagrid('getRows').length;
                for (var i = rowNumber - 1; i >= 0; i--) {
                    comboGrid.datagrid('unselectRow', i);
                    comboGrid.datagrid('deleteRow', i);
                }
            });
        }
        else {
            var btnSearch = comboPanel.find('#_ExChildGridToolbar_Search_' + itemName);
            var txtSearch = '<span>&nbsp;查找&nbsp;</span><input id="_ExChildGridToolbar_SearchText_' + itemName + '" class="easyui-validatebox" type="text" style="width:150px;" />';
            var tipSearch = '<span id="_ExChildGridToolbar_SearchTip_' + itemName + '"></span>';
            btnSearch.before(txtSearch);
            btnSearch.after(tipSearch);
            btnSearch.click(function () {
                var findCount = 0;
                comboGrid.datagrid('unselectAll');
                var searchText = comboPanel.find('#_ExChildGridToolbar_SearchText_' + itemName).val();
                if (searchText != null && searchText != undefined && searchText.length > 0) {

                    var rowList = comboGrid.datagrid('getRows');
                    for (var i = 0; i < rowList.length; i++) {
                        var row = rowList[i];
                        if (row && row.text != null && row.text != undefined && row.text.indexOf(searchText) >= 0) {
                            findCount++;
                            comboGrid.datagrid('selectRow', i);
                        }
                    }
                }

                comboPanel.find('#_ExChildGridToolbar_SearchTip_' + itemName).text("找到" + findCount + "条");
            });
        }
    },

    formatAction: function (parentGridID, itemName, index) {
        var param = '\'' + parentGridID + '\',\'' + itemName + '\', ' + index;
        var link =
            '<a href="#" style="float:left" title="编辑" onclick="comboSerialNumberFunction.beginEdit(' + param + ')"><div class="icon-page-edit"></div></a>' +
            '<a href="#" style="float:left" title="删除" onclick="comboSerialNumberFunction.deleteRow(' + param + ')"><div class="icon-page-delete"></div></a>';
        return link;
    },

    getComboGrid: function (parentGridID, itemName) {
        if (parentGridID == null || parentGridID == undefined || parentGridID.length <= 0) {
            // 控件在From表单中
            return $('#' + itemName).combogrid('grid');
        }
        else {
            // 控件在DataGrid表格中
            var parentGrid = $('#' + parentGridID);
            var parentEditRow = parentGrid.datagrid('getSelected');
            if (!parentEditRow) {
                return null;
            }
            var parentEditIndex = parentGrid.datagrid('getRowIndex', parentEditRow);
            if (parentEditIndex == undefined || parentEditIndex == null) {
                return null;
            }

            var parentEditor = parentGrid.datagrid('getEditor', { index: parentEditIndex, field: itemName });
            if (parentEditor && parentEditor.target) {
                return $(parentEditor.target).combogrid('grid');
            }

            return null;
        }
    },

    endEdit: function (comboGrid, deleteInvalidRow) {
        if (comboGrid && comboGrid.length > 0) {
            var editIndex = comboGrid[0].exEditingRowIndex;
            if (editIndex == undefined || editIndex == null) { return true }
            if (comboGrid.datagrid('validateRow', editIndex)) {
                comboGrid.datagrid('endEdit', editIndex);
                comboGrid[0].exEditingRowIndex = undefined;
                return true;
            } else {
                if (deleteInvalidRow) {
                    comboGrid.datagrid('deleteRow', editIndex);
                    comboGrid[0].exEditingRowIndex = undefined;
                    return true;
                }
                else {
                    return false;
                }
            }
        }
        return true;
    },

    beginEdit: function (parentGridID, itemName, index) {
        var comboGrid = comboSerialNumberFunction.getComboGrid(parentGridID, itemName);
        if (comboGrid && comboGrid.length > 0) {
            var editIndex = comboGrid[0].exEditingRowIndex;
            if (editIndex != index) {
                if (comboSerialNumberFunction.endEdit(comboGrid)) {
                    comboGrid[0].exEditingRowIndex = index;
                    comboGrid.datagrid('selectRow', index).datagrid('beginEdit', index);
                }
            }
        }
    },

    deleteRow: function (parentGridID, itemName, index) {
        var comboGrid = comboSerialNumberFunction.getComboGrid(parentGridID, itemName);
        if (comboGrid && comboGrid.length > 0) {
            comboSerialNumberFunction.endEdit(comboGrid, true);
            comboGrid.datagrid('unselectRow', index);
            comboGrid.datagrid('deleteRow', index);

            // 刷新Grid，解决编辑、删除行时，传入的index不准确的问题
            var rows = comboGrid.datagrid('getRows');
            comboGrid.datagrid('loadData', rows);
        }
    },

    initData: function (element) {
        var text = $(element).combo('getText');

        // 把文本框清空，避免展开Panel时还得根据文本框的值选中所有行，以提高性能
        $(element).combo('setValue', '');

        var data = text;
        if (!data || data.length <= 0) {
            data = [];
        }
        else {
            data = data.split(',');
        }

        var result = [];
        for (var i = 0; i < data.length; i++) {
            if (data[i] != null && data[i] != undefined && data[i].length > 0) {
                result.push({ text: data[i] });
            }
        }

        var comboGrid = $(element).combogrid('grid');
        comboGrid.datagrid('loadData', result);
        $(element).combo('setValue', text);
    },

    saveData: function (element) {
        var comboGrid = $(element).combogrid('grid');
        comboSerialNumberFunction.endEdit(comboGrid, true);

        var result = '';
        var data = comboGrid.datagrid('getRows');
        for (var i = 0; i < data.length; i++) {
            if (data[i] != null && data[i] != undefined) {
                var text = data[i].text;
                if (text != null && text != undefined && text.length > 0) {
                    result += (text + ',');
                }
            }
        }
        result = result.trimEnd(',');
        $(element).combogrid('setValue', result);
    }
};

// 对Combo控件增加清空功能
var comboClearFunction = function (element) {
    var me = this;
    var clearButton;

    this.afterClearValue = null;

    this.doClearValue = function () {
        if ($(element.parentNode).find('.combotree-f').length > 0) {
            if ($(element).combo("options").multiple == true) {
                $(element).combotree('setValues', []);
            }
            else {
                $(element).combotree('setValue', "");
            }
        }
        else if ($(element.parentNode).find('.datebox-f').length > 0) {
            $(element).datebox('setValue', "");
        }
        else if ($(element.parentNode).find('.combogrid-f').length > 0) {
            if ($(element).combo("options").multiple == true) {
                $(element).combogrid('setValues', []);
            }
            else {
                $(element).combogrid('setValue', "");
            }
        }
        else if ($(element.parentNode).find('.combobox-f').length > 0) {
            if ($(element).combo("options").multiple == true) {
                $(element).combobox('setValues', []);
            }
            else {
                $(element).combobox('setValue', "");
            }
        }
        else if ($(element.parentNode).find('.combo-f').length > 0) {
            if ($(element).combo("options").multiple == true) {
                $(element).combo('setValues', []);
            }
            else {
                $(element).combo('setValue', "");
            }
        }

        if (me.afterClearValue) {
            me.afterClearValue();
        }
    };

    this.addClearButton = function () {
        var buttonList = $(element.parentNode).find(".icon-clear-button");

        if (buttonList.length <= 0) {
            element.exComboClear = me;
            me.clearButton = document.createElement('span');
            var comboControl = $(element.parentNode).find(".combo");
            comboControl.after(me.clearButton);
            me.clearButton.className = "icon-clear-button";

            var optionsCombo = $(element).combo("options");
            if (optionsCombo.disabled != true || optionsCombo.exUseOriginDisable) {

                // 禁用Input上面微软自带的Clear按钮
                $(element).combo('textbox').addClass('hide-clear-input');

                me.clearButton.onclick = me.doClearValue;
            }

            if (optionsCombo.disabled == true) {
                $(me.clearButton).hide();
                $(element.parentNode).find(".combo-arrow").css("cursor", "default");
            }
        }
    };

    this.showClearButton = function (newValue) {
        if ($(element).combo("options").disabled != true) {

            if (!me.clearButton) {
                var buttonList = $(element.parentNode).find(".icon-clear-button");
                if (buttonList.length > 0) {
                    me.clearButton = buttonList[0];
                }
            }

            if (me.clearButton) {
                // 显示或隐藏清空按钮
                if (newValue == undefined
                    || newValue == null
                    || newValue.toString().length <= 0) {
                    $(me.clearButton).css('display', 'none');
                }
                else {
                    $(me.clearButton).css('display', 'inline-block');
                }
            }
        }
    };
};

// 对Combo控件增加TextButton功能，以供“选择用户”控件使用
var comboTextButtonFunction = function (element) {
    var me = this;
    var textButton;

    this.addTextButton = function () {
        var buttonList = $(element.parentNode).find(".icon-text-button");

        if (buttonList.length <= 0) {
            var buttonArrow = $(element.parentNode).find(".combo-arrow");
            buttonArrow.addClass("searchbox-button icon-text-button");
            buttonArrow.unbind("click");
            me.textButton = buttonArrow;

            var optionsCombo = $(element).combo("options");
            if (optionsCombo.disabled != true || optionsCombo.exUseOriginDisable) {
                buttonArrow.click(
                    function () {
                        var controlJq = $(element);
                        if (controlJq.combobox("options").disabled == true) {
                            return;
                        }

                        var value = "";
                        var multi = controlJq.combobox("options").multiple;
                        if (controlJq.combobox("options").multiple == true) {
                            value = controlJq.combobox('getValues');
                            if (value.join) {
                                value = value.join(',');
                            }
                        }
                        else {
                            value = controlJq.combobox('getValue');
                        }

                        // 弹出框时，隐藏Combo下拉框
                        controlJq.combo('hidePanel');

                        var newLayer = window.showUserDialog(value, !multi, controlJq.combobox("options").roleID);

                        // 当弹出框选择了用户后，更新父页面的文本框
                        newLayer.updateTextButtonValue = function (selectedOptions) {
                            if ((!selectedOptions) || selectedOptions.length <= 0) {
                                selectedOptions = new Array();
                            }

                            var selectedValues = new Array();
                            var selections = new Array();
                            for (var i = selectedOptions.length - 1; i >= 0; i--) {
                                selectedValues.push(selectedOptions[i].value);
                                selections.push({ value: selectedOptions[i].value, text: selectedOptions[i].text });
                            }

                            var options = $(element).combobox("options");
                            if (!options.data || !options.data.mergeSelections) {
                                options.data = new Array();
                            }
                            options.data = options.data.mergeSelections(selections);
                            $(element).combobox("loadData", options.data);

                            if (me.setComboValue) {
                                me.setComboValue(selectedValues);
                            }

                            top.closeDialog();
                        };
                    }
                );
            }
            else {
                $(buttonArrow).css("cursor", "default");
            }
        }
    };

    this.setComboValue = function (selectedValues) {
        if ($(element).combo("options").disabled != true) {
            if ($(element).combo("options").multiple == true) {
                $(element).combobox('setValues', selectedValues);
            }
            else {
                if (selectedValues == undefined
                    || selectedValues.length <= 0) {
                    $(element).combobox('setValue', "");
                }
                else {
                    $(element).combobox('select', selectedValues[0]);
                    $(element).combobox('setValue', selectedValues[0]);
                }
            }
        }
    };
};

// 对Combo控件增加PopupSelect功能，以供“选择业务数据”控件使用
var comboPopupSelectFunction = function (element, foreignTableID, foreignTableDisplayName, foreignTextItemName) {
    var me = this;
    var popupSelect;
    
    // 外键字段弹出框的额外过滤条件
    this.iExtraFilter = undefined;

    this.addPopupSelect = function () {
        var buttonList = $(element.parentNode).find(".icon-popup-button");

        if (buttonList.length <= 0) {
            var buttonArrow = $(element.parentNode).find(".combo-arrow");
            buttonArrow.addClass("searchbox-button icon-popup-button");
            buttonArrow.unbind("click");
            me.popupSelect = buttonArrow;

            var optionsCombo = $(element).combo("options");
            if (optionsCombo.disabled != true || optionsCombo.exUseOriginDisable) {
                buttonArrow.click(
                    function () {
                        if ($(element).combo("options").disabled == true) {
                            return;
                        }

                        // 验证数据
                        var dependItemValue;
                        if ($(element).combobox("options").dependItemID > 0) {
                            $(element).combo('textbox').validatebox('validate', true);
                            dependItemValue = element.exDependItemValue;

                            // 当依赖栏位为空时，中断弹出动作
                            if (!amCommon.notEmpty(dependItemValue)) {
                                element.exDependItemValue = undefined;
                                return;
                            }
                        }
                        element.exDependItemValue = undefined;

                        var value = "";
                        var valueObj = [];
                        var usageType = 'SingleSelection';
                        var options = $(element).combobox("options");
                        if (options.multiple == true) {
                            usageType = 'MultiSelection';
                            valueObj = $(element).combobox('getValues');
                            value = valueObj;
                            if (value.join) {
                                value = value.join(',');
                            }
                        }
                        else {
                            if ($(element).combo('options').exUsageListFilter == true) {
                                usageType = 'SingleListFilter';
                            }

                            valueObj = $(element).combobox('getValue');
                            value = valueObj;
                        }

                        // 记录下旧的值对象，用于撤销操作时恢复值
                        element.exOldValue = valueObj;

                        // 弹出框时，隐藏Combo下拉框
                        $(element).combo('hidePanel');

                        var newLayer;
                        if (options.foreignViewID > 0) {
                            newLayer = window.showSummaryDialog(options.foreignViewID, foreignTableDisplayName,
                                value, options.dependDecideSummaryItemID, dependItemValue, usageType, me.iExtraFilter);
                        }
                        else if (foreignTableID > 0) {
                            newLayer = window.showBusinessDialog(foreignTableID, foreignTableDisplayName,
                                value, options.dependDecideItemID, dependItemValue, usageType, me.iExtraFilter);
                        }
                        else if (options.foreignTableUrl) {
                            newLayer = window.showBusinessDialog(options.foreignTableUrl, foreignTableDisplayName,
                                value, options.dependDecideItemID, dependItemValue, usageType, me.iExtraFilter);
                        }

                        // 当弹出框点击取消按钮时，撤销对本栏位的修改
                        newLayer.rejectSelectValue = function () {
                            var oldValues = element.exOldValue;
                            if (oldValues == null || oldValues == undefined) {
                                oldValues = new Array();
                            }
                            me.setComboValue(oldValues);

                            top.closeDialog();
                        }

                        // 当弹出框选择了业务数据后，更新父页面的文本框
                        newLayer.updatePopupSelectValue = function (selectedRows, isUnSelect, keepPopupWindow) {
                           
                            if (selectedRows && selectedRows.length > 0) {

                                var selections = new Array();
                                var selectedValues = new Array();
                                for (var i = selectedRows.length - 1; i >= 0; i--) {

                                    var selectRow = selectedRows[i];
                                    
                                    if (selectRow) {
                                        var selectValue = selectRow._ID;
                                        if (selectValue == undefined) {
                                            selectValue = selectRow.id;
                                        } 
                                        var selectText = selectRow[foreignTextItemName];
                                        if (selectText == null) {
                                            selectText = selectRow['SystemName'];
                                        }

                                        selectedValues.push(selectValue);
                                        selections.push({ value: selectValue, text: selectText });
                                    }
                                }

                                var options = $(element).combobox("options");
                                var oldValues = $(element).combobox('getValues');

                                if (!options.data || !options.data.mergeSelections) {
                                    options.data = new Array();
                                }
                                options.data = options.data.mergeSelections(selections);
                                $(element).combobox("loadData", options.data);

                                if (!isUnSelect) {
                                    if (me.setComboValue) {
                                        // 多选情况下将原有值合并进来
                                        if (options.multiple == true) {
                                            selectedValues = selectedValues.merge(oldValues, true);
                                        }
                                        me.setComboValue(selectedValues);
                                        if (options.isGet) {
                                            GetItem(selectedValues);
                                        }
                                    }
                                }
                                else {
                                    for (var i = 0; i < selectedValues.length; i++) {
                                        $(element).combobox("unselect", selectedValues[i]);
                                    }
                                }
                            }

                            if (!keepPopupWindow) {
                                top.closeDialog();
                            }
                        };
                    }
                );
            }
            else {
                $(buttonArrow).css("cursor", "default");
            }
        }
    };

    this.setComboValue = function (selectedValues) {
      
        if ($(element).combo("options").disabled != true) {
            if ($(element).combo("options").multiple == true) {
                if (selectedValues && selectedValues.length > 0) {
                    for (var i = 0; i < selectedValues.length; i++) {
                        $(element).combobox('select', selectedValues[i]);
                    }
                }

                $(element).combobox('setValues', selectedValues);
            }
            else {
                if (selectedValues == undefined
                    || selectedValues.length <= 0) {
                    $(element).combobox('setValue', "");
                }
                else {
                    $(element).combobox('select', selectedValues[0]);
                    $(element).combobox('setValue', selectedValues[0]);
                }
                
            }
        }
    };
};

// 对Combo控件增加Auto Complete输入查询功能，并且校验非法输入
var comboAutoCompleteFunction = function (element, comboClear) {
    var me = this;

    // 外键字段弹出框的额外过滤条件
    this.iExtraFilter = undefined;

    this.onAutoComplete = null;
    this.getRequestUrl = null;
    this.getRequestParam = null;
    this.doAutoComplete = function (valueField, textField, isUserSource, isGridEdit) {
        if (!element
            || !comboClear
            || element.exHasAutoComplete
            || !me.getRequestUrl
            || !valueField
            || !textField) {
            return;
        }

        element.exHasAutoComplete = true;
        comboClear.afterClearValue = function () {
            element.exQueryText = undefined;
        };

        // 解决问题：当输入关键字，通过非起始位置的模糊查询匹配到查询结果时，一闪而过
        $(element).combobox('options').filter = function (q, row) {
            return row['text'].toLowerCase().indexOf(q.toLowerCase()) >= 0;
        }

        $(element).combo('textbox').keyup(function (event) {
            if (!window.typeKeyIsAction(event.keyCode)) {

                var newQueryText = $(element).combo("getText");
                var oldQueryText = element.exQueryText;
                element.exQueryText = newQueryText;
                if (newQueryText == undefined
                    || newQueryText == null
                    || newQueryText.toString().length <= 0) {

                    // 用户手动删除了所有文本时，则把选中值清空
                    comboClear.doClearValue();
                    comboClear.showClearButton();
                    $(element).combobox("loadData", [], true);
                    return;
                }
                else if (oldQueryText == newQueryText) {
                    $(element).combo('showPanel');
                    return;
                }

                comboClear.showClearButton();

                var requestUrl = me.getRequestUrl(newQueryText);
                if (!requestUrl) {
                    return;
                }
                var requestParam = null;
                if (me.getRequestParam) {
                    requestParam = me.getRequestParam(newQueryText);
                }

                $.ajax({
                    type: "POST",
                    url: requestUrl,
                    data: requestParam
                })
                .success(function (result) {
                    if (!result) {
                        return;
                    }

                    var dataRows = result.rows;
                    if (!dataRows) {
                        try {
                            dataRows = eval(result);
                        } catch (ex) {
                            return;
                        }
                    }

                    if (!dataRows) {
                        return;
                    }

                    var itemList = new Array();
                    for (var i = 0; i < dataRows.length; i++) {
                        var row = dataRows[i];
                        if (row) {
                            var value = row[valueField];
                            var text = row[textField];

                            if (value == null) {
                                value = row['ID'];
                            }

                            if (value > 0 && text != undefined && text != null && text.toString().length > 0) {
                                itemList.push({ text: text, value: value });
                            }
                        }
                    }

                    // 用户输入的字符刚刚匹配某项则自动选中
                    var controlText = $(element).combo("getText");
                    var autoSelectedItem = itemList.getSelectionByText(controlText);

                    if (autoSelectedItem) {
                        if (me.onAutoComplete) {
                            me.onAutoComplete([autoSelectedItem.value]);
                        }
                        if (isGridEdit == true) {
                            // 表格编辑中，将选中的选项加入options.data，以供comboLoadMetaFormatter显示之用
                            var options = $(element).combobox("options");
                            if (options) {
                                if (!options.data || !options.data.mergeSelections) {
                                    options.data = new Array();
                                }

                                var newDatas = new Array();
                                newDatas.push(autoSelectedItem);
                                // 不能反着写：newDatas.mergeSelections(options.data)
                                options.data = options.data.mergeSelections(newDatas);
                            }
                        }
                    }

                    $(element).combobox("loadData", itemList, true);

                    if (autoSelectedItem) {
                        $(element).combobox("select", autoSelectedItem.value);
                        $(element).combo("setText", controlText);
                    }
                })
                .error(function (result) {
                    var message = "很抱歉，操作出现异常！请联系管理员。";
                    if (result) {
                        if (result.responseJSON && result.responseJSON.ExceptionMessage) {
                            message = result.responseJSON.ExceptionMessage;
                        }
                        else if (result.responseText) {
                            message = result.responseText;
                        }
                    }
                });
            }
        });
    };

    // 业务数据外键数据源
    this.foreignKeyAutoComplete = function (foreignTableID, foreignTextItemName, isGridEdit) {
        if (element && !(element.exHasAutoComplete) && foreignTextItemName) {
            var options = $(element).combo('options');
            me.getRequestUrl = function (queryText) {
                var url = options.foreignTableApi;
                if (foreignTableID > 0) {
                    url = '/api/ListData/List?FormID=' + foreignTableID + '&IsActive=&ParentTableRecordID=-1';
                }
                return url;
            };

            var statusFilter = '';
            if (!(options.exUsageListFilter)) {
                statusFilter = amCommon.business.selectionFilter();
            }

            me.getRequestParam = function (queryText) {
                return 'rows=15&page=1&filterRules=[' + statusFilter +
                    '{"field":"' + foreignTextItemName + '","op":"contains","value":"' + encodeURIComponent(queryText) + '"}]';
            };

            me.doAutoComplete('_ID', foreignTextItemName, false, isGridEdit);
        }
    };

    // 统计报表数据源
    this.summaryAutoComplete = function (foreignTableID, foreignTextItemName, isGridEdit) {
        if (element && !(element.exHasAutoComplete) && foreignTableID > 0 && foreignTextItemName) {
            me.getRequestUrl = function (queryText) {
                return '/api/SummaryData/SummaryList?FormID=' + foreignTableID;
            };

            var statusFilter = '';
            if (!($(element).combo('options').exUsageListFilter)) {
                statusFilter = amCommon.business.selectionFilter();
            }

            me.getRequestParam = function (queryText) {
                return 'rows=15&page=1&filterRules=[' + statusFilter +
                    '{"field":"' + foreignTextItemName + '","op":"contains","value":"' + encodeURIComponent(queryText) + '"}]';
            };

            me.doAutoComplete('_ID', foreignTextItemName, false, isGridEdit);
        }
    };

    // 用户数据源
    this.userAutoComplete = function () {
        if (element && !(element.exHasAutoComplete)) {
            me.getRequestUrl = function (queryText) {
                var roleList = $(element).combobox('options').roleID;
                var url = '/api/AuthorityUserList/ListQuery';
                if (roleList) {
                    url += '?RoleList=' + roleList;
                }
                return url;
            };
            me.getRequestParam = function (queryText) {
                return 'rows=15&page=1&filterRules=[{"field":"DisplayName","op":"contains","value":"' + encodeURIComponent(queryText) + '"}]';
            };

            me.doAutoComplete('ID', 'DisplayName', true);
        }
    };
};

// 对Combo控件增加禁用功能，隐藏控件，只显示文本
var comboDisableFunction = function () {
    var me = this;
    var textControl = undefined;

    this.disable = function (element, val) {
        var options = $(element).combo("options");
        if (options.disabled == true && !options.exUseOriginDisable) {
            var textControlList = $(element.parentNode).find(".ex-text-control");
            if (textControlList.length > 0) {
                me.textControl = textControlList[0];
            }
            else {
                me.textControl = document.createElement("span");
                me.textControl.className = "ex-text-control";
                $(element.parentNode).prepend(me.textControl);
            }

            me.textControl.innerText = val;
            $(element.parentNode).find(".combo").hide();
        }
    };
};

// 对TextBox控件增加禁用功能，隐藏控件，只显示文本
var textboxDisableFunction = function () {
    var me = this;
    var textControl = undefined;

    this.disable = function (element, val) {
        // change
        var textbox = $(element);
        var options = ($(element).attr("class").indexOf('textbox-f') > 0 ?
            textbox.textbox("options") :
            textbox.validatebox("options")
            );
        if (options.disabled == true && !options.exUseOriginDisable) {

            var container = $(element.parentNode);
            if (textbox.attr('class').indexOf('numberbox-f') >= 0) {
                textbox.hide();
                textbox = container.find(".numberbox");
            }

            var textControlList = container.find(".ex-text-control");
            if (textControlList.length > 0) {
                me.textControl = textControlList[0];
            }
            else {
                me.textControl = document.createElement("span");
                me.textControl.className = "ex-text-control";
                container.prepend(me.textControl);
            }

            if (textbox.prop('nodeName') == "TEXTAREA") {
                me.textControl.innerHTML = val;
            }
            else {
                me.textControl.innerText = val;
            }
            textbox.hide();
        }
    };
};

// 自动计算列处理程序
function autoComputeFields(form, target, first, operator, second) {
    if (form && target &&
        first && second && operator) {
        var prefix = "#form" + form + "_";

        var targetField = $(prefix + target);
        var firstField = $(prefix + first);
        var secondField = $(prefix + second);
        if (targetField.length > 0 && targetField.numberbox
            && firstField.length > 0 && firstField.numberbox
            && secondField.length > 0 && secondField.numberbox) {
            firstField[0].exEventChange = autoCompute;
            secondField[0].exEventChange = autoCompute;
        }

        function autoCompute() {
            var firstValue = firstField.numberbox('getValue');
            var secondValue = secondField.numberbox('getValue');
            if (operator == "+") {
                targetField.numberbox('setValue', firstValue + secondValue);
            }
            else if (operator == "*") {
                targetField.numberbox('setValue', firstValue * secondValue);
            }
        }
    }
}